package com.tjbklx1.rocketMQTest.demo01;

import java.util.List;
import java.util.UUID;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import com.tjbklx1.rocketMQTest.constant.Host;

public class PushConsumer {
	public static void main(String[] args) throws MQClientException, InterruptedException {
		// 生成Consumer
		DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(Host.PUSH_CONSUMER_GROUP);
		// 配置Consumer
		consumer.setInstanceName(UUID.randomUUID().toString());
		consumer.setMessageModel(MessageModel.BROADCASTING);
		consumer.setConsumeMessageBatchMaxSize(32);
		consumer.setNamesrvAddr(Host.HOST);
		consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

		MessageListenerConcurrently listener = new MessageListenerConcurrently() {
			@Override
			public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list,
					ConsumeConcurrentlyContext consumeConcurrentlyContext) {
				// 消费消息
				for (MessageExt me : list) {
					System.out.print("msg=" + new String(me.getBody()) + "\n");
				}
				return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
			}
		};

		consumer.registerMessageListener(listener);
		// 启动Consumer
		consumer.subscribe(Host.TOPIC, "*");
		consumer.start();
		// 停止Consumer
		Thread.sleep(60000);
		consumer.shutdown();
	}

}